﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JigLibX.Physics;
using JigLibX.Geometry;
using JigLibX.Math;
using JigLibX.Utils;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace RPG
{
    public class CGameController : Controller
    {
        private CGamePlayer m_Player;
        private KeyboardState m_OldKS;
        private KeyboardState m_NewKS;

        public CGamePlayer Player
        {
            set
            {
                m_Player = value;
            }
            get
            {
                return m_Player;
            }
        }

        public CGameController(CGamePlayer _player)
        {
            m_Player= _player;
            EnableController();
        }

        public override void UpdateController(float dt)
        {
            if (m_Player == null)
                return;

            m_OldKS = m_NewKS;
            m_NewKS = Keyboard.GetState();

            Body b = m_Player.Entity.Body;

            if (m_NewKS.IsKeyDown(Keys.W))
            {
                Vector3 mov = new Vector3(0, 0, m_Player.Entity.EntityData.MoveSpeed * dt);
                mov = Vector3.Transform(mov, Matrix.CreateFromQuaternion(m_Player.Entity.Rotation));
                mov = new Vector3(mov.X, b.Velocity.Y, mov.Z);
                b.Velocity = mov;
            }

            if (m_NewKS.IsKeyDown(Keys.S))
            {
                Vector3 mov = new Vector3(0, 0, -m_Player.Entity.EntityData.MoveSpeed / 2 * dt);
                mov = Vector3.Transform(mov, Matrix.CreateFromQuaternion(m_Player.Entity.Rotation));
                mov = new Vector3(mov.X, b.Velocity.Y, mov.Z);
                b.Velocity = mov;
            }
            else
            {
                if (!m_NewKS.IsKeyDown(Keys.W))
                    b.Velocity = new Vector3(0, b.Velocity.Y, 0);
            }


            if (m_NewKS.IsKeyDown(Keys.A))
            {
                b.AngularVelocity = new Vector3(0, m_Player.Entity.EntityData.TurnSpeed * dt, 0);
            }

            if (m_NewKS.IsKeyDown(Keys.D))
            {
                b.AngularVelocity = new Vector3(0, -m_Player.Entity.EntityData.TurnSpeed * dt, 0);
            }
            else
            {
                if (!m_NewKS.IsKeyDown(Keys.A))
                    b.AngularVelocity = Vector3.Zero;
            }
        }
    }
}
